import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

public class Solution1298 {
    public int maxCandies(int[] status, int[] candies, int[][] keys, int[][] containedBoxes, int[] initialBoxes) {
        Queue<Integer> queue=new LinkedList<>();
        for (int initialBox : initialBoxes) {
            queue.offer(initialBox);
        }
        Set<Integer> set=new HashSet<>();
        int ans=0;
        while (!queue.isEmpty()){
            int p=queue.poll();
            if (status[p]==0){
                set.add(p);
                continue;
            }
            ans+=candies[p];
            for (int containedBox : containedBoxes[p]) {
                queue.offer(containedBox);
            }
            for (int i : keys[p]) {
                status[i]=1;
                if (set.contains(i)){
                    queue.offer(i);
                    set.remove(i);
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1298().maxCandies(new int[]{1,0,1,0},new int[]{7,5,4,100},new int[][]{{},{},{1},{}},new int[][]{{1,2},{3},{},{}},new int[]{0}));
    }
}
